package cn.broadsense.web.controller;

import cn.broadsense.common.annotation.Log;
import cn.broadsense.common.constant.HttpStatus;
import cn.broadsense.common.core.domain.R;
import cn.broadsense.common.core.domain.entity.SysRole;
import cn.broadsense.common.core.domain.entity.SysUser;
import cn.broadsense.common.core.domain.model.LoginUser;
import cn.broadsense.common.core.redis.RedisCache;
import cn.broadsense.common.enums.BusinessType;
import cn.broadsense.common.enums.OperatorType;
import cn.broadsense.common.utils.SecurityUtils;
import cn.broadsense.common.utils.Sm4SecurityUtil;
import cn.broadsense.framework.web.service.TokenService;
import cn.broadsense.system.mapper.SysUserMapper;
import cn.broadsense.system.service.ISysConfigService;
import cn.broadsense.system.service.ISysUserService;
import cn.broadsense.web.controller.body.UpdatePasswordBody;
import cn.broadsense.web.controller.vo.UserVO;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author huangjinshi
 * @description 个人中心模块接口
 * @createDate 2023-09-12 11:06:33
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/user")
@Api(tags = "个人中心模块")
public class UserController {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisCache redisCache;


    /**
     * 获取个人信息
     *
     * @return
     */
    @ApiOperation("获取个人信息")
    @GetMapping("/info")
    public R<UserVO> getUserInfo() {
        UserVO data = new UserVO();
        String username = SecurityUtils.getUsername();
        SysUser sysUser = sysUserService.selectUserByUserName(username);
        if (Objects.isNull(sysUser)) {
            return R.fail(HttpStatus.UNAUTHORIZED, "获取用户信息异常");
        }
        data.setUserName(sysUser.getUserName());
        data.setNickName(sysUser.getNickName());
        data.setSex(sysUser.getSex());
        data.setPhonenumber(sysUser.getPhonenumber());

        List<SysRole> roles = sysUser.getRoles();
        if (!roles.isEmpty()) {
            String roleName = roles.stream().map(SysRole::getRoleName).collect(Collectors.joining("，"));
            data.setRoleName(roleName);
        }
        if (sysUser.getDept() != null) {
            data.setDeptName(sysUser.getDept().getDeptName());
        }
        if (sysUser.getArea() != null) {
            data.setAreaName(sysUser.getArea().getName());
        }
        return R.ok(data);
    }

    @PostMapping("/updatePassword")
    @ApiOperation("修改密码")
    @Log(title = "修改密码", businessType = BusinessType.UPDATE, operatorType = OperatorType.MOBILE, isSaveRequestData = false, isSaveResponseData = false)
    public R updatePassword(@Valid @RequestBody UpdatePasswordBody body) {
        String newPassword = body.getNewPassword();
        String oldPassword = body.getOldPassword();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            return R.fail("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            return R.fail("修改密码失败，新密码不能与旧密码相同");
        }
        if (sysUserService.resetUserPwd(SecurityUtils.getUsername(), SecurityUtils.encryptPassword(newPassword)) > 0) {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword));
            tokenService.setLoginUser(loginUser);
            return R.ok("修改密码成功");
        }
        return R.fail("修改密码异常，请联系管理员");
    }

    @ApiOperation("获取个人信息")
    @GetMapping("/initAllSM4")
    public void initAllSM4() {
        Object cacheObject = redisCache.getCacheObject("vt:init");
        if (cacheObject != null) {
            return;
        }
        List<SysUser> listUser = sysUserService.listAll();
        if (CollUtil.isNotEmpty(listUser)) {
            for (SysUser sysUser : listUser) {
                try {
                    if (StrUtil.isNotBlank(sysUser.getPhonenumber())) {
                        sysUser.setPhonenumber(Sm4SecurityUtil.encrypt(sysUser.getPhonenumber()));
                    }
                    if (StrUtil.isNotBlank(sysUser.getEmail())) {
                        sysUser.setEmail(Sm4SecurityUtil.encrypt(sysUser.getEmail()));
                    }
                    userMapper.updateUser(sysUser);
                } catch (Exception e) {
                    log.error("加密失败：{}", e.getMessage());

                }
            }
        }
        redisCache.setCacheObject("vt:init", 1);
    }



    @ApiOperation("获取H5页面地址")
    @GetMapping("/getH5Url")
    public R<String> getH5Url() {
        String appH5Url = configService.selectConfigByKey("app_h5_url");
        return R.ok(appH5Url);
    }
}

